package pers.xiaojun.boot.security.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import pers.xiaojun.boot.common.biz.system.oauth2.OAuth2TokenCommonApi;
import pers.xiaojun.boot.common.biz.system.permission.PermissionApi;
import pers.xiaojun.boot.security.config.properties.SecurityProperties;
import pers.xiaojun.boot.security.filter.TokenAuthenticationFilter;
import pers.xiaojun.boot.security.handler.AccessDeniedHandlerImpl;
import pers.xiaojun.boot.security.handler.AuthenticationEntryPointImpl;
import pers.xiaojun.boot.security.service.SecurityPermission;

/**
 * 描述
 *
 * @author xiaojun
 * @since 2025-10-03
 */
@AutoConfiguration
@AutoConfigureOrder(-1)
@EnableConfigurationProperties(SecurityProperties.class)
@RequiredArgsConstructor
public class SecurityAutoConfiguration {


    private final SecurityProperties securityProperties;

    /**
     * 配置密码加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(securityProperties.getPasswordEncoderLength());
    }

    /**
     * 权限校验器
     *
     * @param permissionApi 权限校验接口
     */
    @Bean(name = "ss")
    public SecurityPermission securityPermission(PermissionApi permissionApi) {
        return new SecurityPermission(permissionApi);
    }

    /**
     * 无权限处理器
     */
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedHandlerImpl();
    }

    /**
     * 未登录处理器
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new AuthenticationEntryPointImpl();
    }

    /**
     * Token 过滤器
     */
    @Bean
    public TokenAuthenticationFilter tokenAuthenticationFilter(OAuth2TokenCommonApi authTokenApi) {
        return new TokenAuthenticationFilter(securityProperties, authTokenApi);
    }


}
